package deposito.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import deposito.dto.Log;
import deposito.entities.LogEntity;


@Stateless
public class LogDAO implements ILogDAO {
	
	//Entity Manager
	@PersistenceContext(unitName="IA_DS")
	private EntityManager manager;
	
	
	//persistirLog
	@Override
	public void persistirLog(Log logueo) {
		manager.persist(this.toEntity(logueo));
	}

	//obtenerLogs
	@SuppressWarnings("unchecked")
	@Override
	public List<Log> obtenerLogs(Date fechaInicial, Date fechaFinal) 
	{
		List<Log> lista = new ArrayList<Log>();

		Query q = manager.createQuery("FROM LogEntity lE WHERE lE.fecha between ? and ?");
		
		List<LogEntity> listaE = (List<LogEntity>) q.setParameter(1, fechaInicial).setParameter(2, fechaFinal).getResultList();
		if (listaE != null){
			for(LogEntity elemE : listaE){
				Log elem = new Log();
				elem.setId(elemE.getId());
				elem.setFecha(elemE.getFecha());
				elem.setMensaje(elemE.getMensaje());
				lista.add(elem);
			}
		}
				
		return lista;
	}
	
	//getLogs
	public List<Log> getLogs(){
		List<Log> lista = new ArrayList<Log>();

		Query q = manager.createQuery("FROM LogEntity lE");
		
		@SuppressWarnings("unchecked")
		List<LogEntity> listaE = (List<LogEntity>) q.getResultList();
		if (listaE != null){
			for(LogEntity elemE : listaE){
				Log elem = new Log();
				elem.setId(elemE.getId());
				elem.setFecha(elemE.getFecha());
				elem.setTipo(elemE.getTipo());
				elem.setMensaje(elemE.getMensaje());
				lista.add(elem);
			}
		}	
		return lista;
	}
	
	//***************************************//
	
	//toEntity
	public LogEntity toEntity(Log logueo)
	{
		LogEntity lE = new LogEntity();
		
		lE.setFecha(logueo.getFecha());
		lE.setMensaje(logueo.getMensaje());
		lE.setTipo(logueo.getTipo());
		
		return(lE);
	}

	
}
